#pragma once
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>

#include "Vehicle.h"
#include "Repaired.h"

using namespace std;

class VehicleRegister
{
private:
	vector<Vehicle> v;
	string name;
public:

	VehicleRegister()
	{
		name = "N/A";
	}

	VehicleRegister(string name)
	{
		this->name = name;
	}

	~VehicleRegister(){}

	void Add(Vehicle v)
	{
		this->v.push_back(v);
	}

	void Delete(int i)
	{
		v.erase(v.begin() + i);
	}

	string List()
	{
		ostringstream oss;
		oss << name << endl;
		for (int i = 0; i < v.size(); i++)
		{
			oss << i << ": " << v[i] << endl;
		}
		return oss.str();
	}

	void WriteToFile(string fileName)
	{
		ofstream fout(fileName);
		fout << "VehicleRegister=(" << name << ")" << endl;
		for (auto veh : v)
		{
			fout << "Vehicle=" << veh << endl;
		}
	}

	void ReadFromFile(string fileName)
	{
		ifstream fin;
		string str, row;
		v.clear();

		try
		{
			fin.open(fileName);
			while (getline(fin, row))
			{
				istringstream iss(row);
				getline(iss, str, '=');
				if (str.compare("VehicleRegister") == 0)
				{
					getline(iss, str, '(');
					getline(iss, name, ')');
				}
				else if (str.compare("Vehicle") == 0)
				{
					Vehicle veh;
					iss >> veh;
					if (veh.getYear() != -1)
					{
						v.push_back(veh);
					}
				}
				
			}
		}
		catch (exception e)
		{
			cout << "Error when reading from file " << fileName << endl;
			cout << e.what();
		}
	}

	double CalculateStorageValue()
	{
		double total = 0;
		for (auto veh : v)
		{
			total += veh.getPurchasingPrice();
		}
		return total;
	}

	string FindVehicles(string brand, int year)
	{
		ostringstream oss;
		for (auto veh : v)
		{
			if (veh.getBrand() == brand && veh.getYear() == year)
			{
				oss << name << ": " << veh << endl;
			}
		}
		return oss.str();
	}

	void AddRepair(int i, Repaired r)
	{
		v[i].addRepairs(r);
	}

	string GetName()
	{
		return name;
	}

	void Read()
	{
		cout << "Name: ";
		getline(cin, name);
	}
};

